var index;
var index1;
var index2;
$(function(){
  $.ajax({
    type : "get",
    url : "getLoginInfo.do",
    async : false,
    success : function(v) {
      $("#userName").text(v.userId);
      $("#loginUserId").val(v.userId);
      $("#loginUserRoleId").val(v.roleId);
      $("#userId").val(v.id);
      $("#userDept").val(v.userDept);
      var dept = $("#userDept").val();
      var loginUserRoleId = $("#loginUserRoleId").val();
      if(dept != 0 && checkDept(dept) != 2 && loginUserRoleId != -1 && loginUserRoleId != 2 && loginUserRoleId != 4){
        toastrComponent.show("warning", "对不起你没有权限！");
        return;
      }
      initTab("");
      searchBtnInit();
      initBigType();
      doBtnInit();
    }
  });

  layui.use(['upload','layer'], function(){
    var upload = layui.upload;
    var layer = layui.layer;
    upload.render({
      elem: '#test2'
      ,url: '/upload.do'
      ,multiple: true
      ,size: 10240 //限制文件大小，单位 KB
      ,accept: 'file'
      ,exts: 'jpg|jpeg|png|bmp|'
      ,number: 5
      ,before: function(obj){
        layer.load(); //上传loading
        var fileTypeId = $("#kitSignId").val();
        var realSignId = $("#realSignId").val();
        this.data={'fileTypeId': fileTypeId,"fileType":2,"qymark":1,"realSignId":realSignId};
      }
      ,done: function(res){
        $("#kitUl").html(getKitHtml(res.data));
        //上传完毕
        layer.closeAll('loading');
      }
    });
  });

  $("#kitUl").on("click",".kitUrl",function(){
    var id = $(this).attr("id");
    window.open("/showImage.do?id=" + id);
  });

  $("#kitUl").on("click",".deleteKit",function(){
    var id = $(this).attr("id");
    var li = $(this).parent();
    swal({
      title: "你确定要删除该附件？",
      type: "warning",
      allowOutsideClick: true,
      showConfirmButton: true,
      showCancelButton: true,
      confirmButtonClass: "layui-btn layui-btn-warm",
      cancelButtonClass: "layui-btn layui-btn-primary",
      confirmButtonText: "确认",
      cancelButtonText: "取消"
    }, function (o) {
      if (o) {
        $.ajax({
          type: "get",
          url: "deleteKit.do",
          data: {
            "id": id
          },
          success: function (data) {
            if (data == "success") {
              li.remove();
              toastrComponent.show("success", "删除成功!");
            }
          }
        });
      }
    });
  });
});


function doBtnInit() {
  //附件弹框
  $("#applySignTableDiv").on("click",".kit",function () {
    var applyId = $(this).attr("applyId");
    var signId = $(this).attr("signId");
    $("#kitSignId").val(applyId);
    $("#realSignId").val(signId);
    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index5 = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:'附件信息',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen5')//打开的内容
      });
    });

    $.ajax({
      type: "get",
      url: "getApplyKitList.do",
      data: {
        "fileType": 2,
        "signId": signId
      },
      success: function (data) {
        $("#kitUl").html(getKitHtml(data));
      }
    });

  });
  //审批按钮弹框
  $("#applySignTableDiv").on("click",".approvalApplySign",function () {
    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index1 = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:'审批签约客户',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen1')//打开的内容
      });
    });

    var applySignId = $(this).attr("applySignId");
    var approvalState = $(this).attr("approvalState");

    $("#approvalSignId").val(applySignId);
    $("#approvalSignState").val(approvalState);
  });

  //审批界面关闭
  $("#cancelApprovalBtn").on("click", function () {
    layer.close(index1);
  });
  //保存审批结果
  $("#saveApproval").on("click",function () {
    var applySignId = $("#approvalSignId").val();
    var approvalState = $("#approvalSignState").val();
    var approvalResult = $("input[name='approvalResult']:checked").val();
    var approvalAdvice = $("#approvalAdvice").val();
    if(approvalAdvice == ""){
      toastrComponent.show("warning", "请填写审批意见！");
      return;
    }
    $.ajax({
      type: "get",
      url: "doApplyApproval.do",
      data: {
        "applySignId": applySignId,
        "approvalState": approvalState,
        "approvalResult":approvalResult,
        "approvalAdvice":approvalAdvice
      },
      success: function (data) {
        if (data == "success") {
          tablerelaod("applySignTab");
          toastrComponent.show("success", "审批成功");
          $("#approvalAdvice").val("");
          var form = layui.form;
          form.val("approvalForm", {
            "approvalResult": "1"
          })
        }
        layer.close(index1);
      }
    });
  });

  //显示审批记录
  $("#applySignTableDiv").on("click",".showApproval",function () {
    var applySignId = $(this).attr("applySignId");
    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index2 = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:'审批记录',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen2')//打开的内容
      });
    });

    $.ajax({
      type: "get",
      url: "getApplyApprovalBySignId.do",
      data: {
        "applySignId": applySignId
      },
      success: function (data) {
          var html = "";
          if(data.length == 0){
            html += '<li class="layui-timeline-item"><i class="layui-icon layui-timeline-axis"></i>' +
                '<div class="layui-timeline-content layui-text"><h3 class="layui-timeline-title">无</h3></div></li>'
          }else {
            $.each(data,function (index,item) {
              if(item.approvalResult == "发起审批"){
                html += '<li class="layui-timeline-item"><i class="layui-icon layui-timeline-axis"></i>' +
                    '<div class="layui-timeline-content layui-text"><h3 class="layui-timeline-title">'+item.approvalTime+'</h3><p><span style="">' +
                    item.approvalUserName + '&nbsp;</span>发起了转款审批流程' + '<br></p></div></li>'
              }else{
                html += '<li class="layui-timeline-item"><i class="layui-icon layui-timeline-axis"></i>' +
                    '<div class="layui-timeline-content layui-text"><h3 class="layui-timeline-title">'+item.approvalTime+'</h3><p><span style="">' +
                    item.approvalUserName + '&nbsp;</span>审批了你的转款申请，审批结果为：' + item.approvalResult +
                    '<br>审批意见：' + item.approvalAdvice
                    + '</p></div></li>'
              }
            })
          }

        $("#approvalList").html(html);

      }
    });

  });

  //详情
  $("#applySignTableDiv").on("click",".detailApplySign",function () {
    var signId = $(this).attr("signId");

    layui.use(['layer'],function () {
      var layer = layui.layer,$=layui.$;
      index = layer.open({
        type:1,//类型
        area: ['auto', 'auto'],//定义宽和高
        title:'签约客户详情',//题目
        shadeClose:false,//点击遮罩层关闭
        zIndex: 1,
        content: $('#layerOpen')//打开的内容
      });
    });
    layui.use(['table'], function() {
      var table = layui.table;
      table.render({
        elem: '#qyTab'
        , url: 'getSignType.do?signId=' + signId
        ,page: {
          layout: ['count', 'prev', 'page', 'next', 'skip']
          , groups: 1 //只显示 1 个连续页码
          , first: false //不显示首页
          , last: false //不显示尾页
          , limit: 5
          , limits: [5]
        }
        , cols: [[
          {field: 'bigType', align: 'center', width: '20%', title: '大类'}
          ,{field: 'smallType', align: 'center', width: '19.4%', title: '小类'}
          ,{field: 'purpose', align: 'center', width: '6%', title: '用途'}
          ,{field: 'project', align: 'center', width: '10%', title: 'B证'}
          ,{field: 'initStatus', align: 'center', width: '6%', title: '状态'}
          ,{field: 'price', align: 'center', width: '10%', title: '价格'}
          , {field: 'peopleNum', align: 'center', width: '5%',title: '人数'}
          , {field: 'firstPrice', align: 'center', width: '8%', title: '预付款'}
          , {field: 'scendPrice', align: 'center', width: '8%', title: '中期款'}
          , {field: 'thirdPrice', align: 'center', width: '8%', title: '尾款'}
        ]]

      });
    })
    var applySignId = $(this).attr("applySignId");
    //回款人才信息
    layui.use(['table'], function() {
      var table = layui.table;
      table.render({
        elem: '#rcTab'
        , url: 'getSignCustomById.do?id=' + applySignId
        , cols: [[
          {field: 'name', align: 'center', width: '15%', title: '名称'}
          ,{field: 'phone', align: 'center', width: '15%', title: '电话'}
          , {field: 'bigType', align: 'center', width: '20%',title: '大类'}
          , {field: 'smallType', align: 'center', width: '20%', title: '小类'}
          , {field: 'price', align: 'center', width: '10%', title: '价格'}
          , {field: 'unit', align: 'center', width: '10%', title: '年限',templet: function (data) {
            var chUnit;
            if(data.unit == 1){
              chUnit="一年";
            }else if(data.unit == 2){
              chUnit="两年";
            }else if(data.unit == 3){
              chUnit="三年";
            }
            return  chUnit;
          }}
          , {field: 'createUserName', align: 'center', width: '10.2%', title: '录入人'}
        ]]

      });
    })

  });

}

//初始化大类小类
function initBigType() {
  $.ajax({
    type: "get",
    url: "getAllBigType.do",
    success: function (data) {
      var html =  '<option value="">选择或搜索</option>';
      $.each(data, function (i, item) {
        html += '<option value="'+item.id+'">'+item.typeName+'</option>';
      });
      $("#bigType").html(html);

      layui.use(['form'], function () {
        var form = layui.form;
        form.on('select(bigType)', function(data){
          $.ajax({
            type: "get",
            url: "getAllSmallType.do?parentId=" + data.value,
            success: function (smallData) {
              var smallhtml =  '<option value="">选择或搜索</option>';
              $.each(smallData, function (i, item) {
                smallhtml += '<option value="'+item.id+'">'+item.typeName+'</option>';
              });
              $("#smallType").html(smallhtml);

              form.render('select');
            }
          });
        });
      });
    }
  });
}


//搜索按钮事件
function searchBtnInit() {
	$("#searchBtn").on("click",function () {
		var serachStr = $("#searchStr").val();
    initTab(serachStr);
  });
}


function setNull() {
  $("#name").val("");
  $("#phone").val("");
  $("#price").val("");
  $("#mark").val("");
  $("#smallType").html("");
  var form = layui.form;
  form.val("signForm", {
    "purpose": ""
    ,"bigType": ""
    ,"smallType": ""
    ,"project": ""
    ,"initStatus": ""
  })
}

//初始化表格
function initTab(search) {
  layui.use(['table'], function() {
    var table = layui.table;
    table.render({
      elem: '#applySignTab'
      , url: 'getApplySignList.do?search=' + search + '&applyTypeId=2'
      , height: '480',
      page: {
        layout: ['count', 'prev', 'page', 'next', 'skip']
        , groups: 1 //只显示 1 个连续页码
        , first: false //不显示首页
        , last: false //不显示尾页
        , limit: 10
        , limits: [10]
      }
      , cols: [[
        {field: 'name', align: 'center', width: '15%', title: '名称'}
        ,{field: 'phone', align: 'center', width: '10%', title: '电话'}
        , {field: 'applyType', align: 'center', width: '8%', title: '转款类型'}
        , {field: 'applyPrice', align: 'center', width: '8%', title: '转款金额',
          templet: function (data) {
          var html = '<span style="color: red;">'+data.applyPrice+'</span>';
          return html;
        }}
        , {field: 'applyMark', align: 'center', width: '13%', title: '转款备注'}
        , {field: 'applyCreateTime', align: 'center', width: '13%', title: '转款时间'}
        , {field: 'createUserName', align: 'center', width: '8%', title: '录入人员'}
        , {field: 'kit', align: 'center', width: '10%', title: '附件',templet: function (data) {
          var html = '<a class="layui-btn layui-btn-xs kit" lay-event="edit" signId='+data.signId+' applyId='+data.applyId+' >附件信息</a>';
          return html;
        }}
        , {
          field: 'id', align: 'center', width: '15.4%', title: '操作',
          templet: function (data) {
            var html = '';
            var loginUserRoleId = $("#loginUserRoleId").val();
            var loginUserId = $("#userId").val();
            if(data.applyState == loginUserRoleId){
              html += '<a class="layui-btn layui-btn-xs detailApplySign" lay-event="edit" signId='+data.signId+'  applySignId='+data.applyId+' approvalState='+data.applyState+'>详情</a>';
              html += '<a class="layui-btn layui-btn-xs approvalApplySign" lay-event="edit" style="background-color: #1E9FFF;" applySignId='+data.applyId+' approvalState='+data.applyState+'>审批</a>';
              html += '<a class="layui-btn layui-btn-xs showApproval" lay-event="edit" applySignId='+data.applyId+' approvalState='+data.applyState+'>审批记录</a>';
            }else {
                if(data.applyState == 5){
                  html += '<a class="layui-btn layui-btn-xs detailApplySign" lay-event="edit" signId='+data.signId+'  applySignId='+data.applyId+' approvalState='+data.applyState+'>详情</a>';
                  html += '<a class="layui-btn layui-btn-xs" style="background-color: #FF5722;" lay-event="edit" applySignId='+data.applyId+' approvalState='+data.applyState+'>审批完成</a>';
                  html += '<a class="layui-btn layui-btn-xs showApproval" lay-event="edit" applySignId='+data.applyId+' approvalState='+data.applyState+'>审批记录</a>';
                }else{
                  html += '<a class="layui-btn layui-btn-xs detailApplySign" lay-event="edit" signId='+data.signId+'  applySignId='+data.applyId+' approvalState='+data.applyState+'>详情</a>';
                  html += '<a class="layui-btn layui-btn-xs showApproval" lay-event="edit" applySignId='+data.applyId+' approvalState='+data.applyState+'>审批记录</a>';
                }
            }
            return html;
          }
        }
      ]]
    });
  })
}


function tablerelaod(tableId) {
  var table = layui.table;
  table.reload(tableId);
}